<template>
  <div class="modal_table_only">
    <ProTable
      ref="tableRef"
      :fetchListApi="_pushLogCheck"
      :columns="columns"
      row-key="configPushId"
      hide-search
      :row-class-name="
        (record) =>
          record.message &&
          record.message.indexOf('%') != -1 &&
          record.monitorStatus == 1
            ? 'warning-row'
            : ''
      "
    >
    </ProTable>
  </div>
</template>

<script setup lang="tsx">
import { computed, onBeforeUnmount, ref } from 'vue';
import { Tag } from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { listToEnum } from '@/utils/utils';
import { fetchDictOfType } from '@/api/dict';
import { pushLogCheck } from '@/api/push';

defineOptions({
  name: 'PushDevice',
});

interface Props {
  pageData: any;
}
const props = defineProps<Props>();

const tableRef = ref();
const sysOnlineModeEnum = ref<Record<string, any>>({});
const init = () => {
  fetchDictOfType('sys_on_line_status').then((res: any) => {
    sysOnlineModeEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
  });
};
init();

let timer = setInterval(() => {
  tableRef.value.refresh(false);
}, 5000);
onBeforeUnmount(() => {
  clearTimeout(timer);
});
const _pushLogCheck = async (params: any) => {
  const { configPushTotalId, upgradeStatus } = props.pageData;
  const res: any = await pushLogCheck({
    ...params,
    configPushTotalId,
    upgradeStatus,
  });
  if (res.rows.length > 0) {
    const result = res.rows.every((item: any) => {
      return item.message == '下载成功';
    });
    result && clearTimeout(timer);
  }
  return res;
};
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
  },
  {
    title: '设备型号',
    dataIndex: 'model',
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
  },
  {
    title: '推送结果',
    dataIndex: 'upgradeStatus',
    width: 100,
    customRender({ text }) {
      return text == '1' ? (
        <span style='color: #67c23a'>成功</span>
      ) : text == '0' ? (
        <span style='color: #f56c6c'>失败</span>
      ) : (
        <span style='color: #F9AE18'>等待中</span>
      );
    },
  },
  {
    title: '状态',
    dataIndex: 'onlineStatus',
    width: 100,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'error' : 'success'}>
          {
            sysOnlineModeEnum.value?.[
              text as keyof typeof sysOnlineModeEnum.value
            ]
          }
        </Tag>
      );
    },
  },
]);
</script>
<style lang="scss" scoped>
:deep(.warning-row) {
  color: #ff4444;
}
</style>
